﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Input;
using Labb_3.Model;

namespace Labb3.Model
{
    class BallSimulation
    {
        public List<Ball> _ballList = new List<Ball>();
        public MouseRectangle _mouseRect;
        //private float mouseRectSize = 0.05f;
        private const int _numberOfBalls = 15;

        public BallSimulation()
        {
            for (int i = 0; i < _numberOfBalls; i++)
            {
                Ball ball = new Ball(new Vector2(0.5f, 0.5f), i);
                _ballList.Add(ball);
            }
        }

        public void Update(Vector2 mousePos, MouseRectangle mouseRect)
        {
            //_mouseRect = MouseRectangle.GetMouseRectangle(mousePos);
            _mouseRect = mouseRect;

            foreach(Ball ball in _ballList)
            {
                ball._position += ball._speed;
                CollisionHandling(ball);
            }
        }

        public void CollisionHandling(Ball ball)
        {
            if (ball._position.X + (float)ball._diameter > 1f)
            {
                ball._speed.X = ball._speed.X * -1;
            }
            else if (ball._position.X < 0f)
            {
                ball._speed.X = ball._speed.X * -1;
            }
            if (ball._position.Y + (float)ball._diameter > 1f)
            {
                ball._speed.Y = ball._speed.Y * -1;
            }
            else if (ball._position.Y < 0f)
            {
                ball._speed.Y = ball._speed.Y * -1;
            }
        }

        public void CheckForKill() 
        {
            Console.WriteLine("Musens Position: " + _mouseRect.TopLeft + "\nMusen Left: " + _mouseRect.Left + "\nMusen Right: " + _mouseRect.Right + "\nMusen Top: " + _mouseRect.Top + "\nMusen Bot: " + _mouseRect.Bottom);
            for (int i = _ballList.Count; i-- > 0; )
            {
                Console.WriteLine("Bollens Position" + _ballList[i]._position);
                if (_ballList[i]._position.X > _mouseRect.Left && _ballList[i]._position.X + (_ballList[i]._diameter) < _mouseRect.Right)
                {
                    if (_ballList[i]._position.Y > _mouseRect.Top && _ballList[i]._position.Y + (_ballList[i]._diameter) < _mouseRect.Bottom)
                    {
                        RemoveBall(_ballList[i]);
                    }
                }
            }
        }

        public void RemoveBall(Ball ballToRemove) 
        {
            System.Diagnostics.Debug.WriteLine("Död!");
            _ballList.Remove(ballToRemove);
        }
    }
}
